package com.study.talk.netty;

import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.Service;
import android.content.Intent;
import android.content.pm.ServiceInfo;
import android.os.Build;
import android.os.IBinder;
import android.util.Log;

import com.study.talk.R;

public class NettyService extends Service {

    private static final String TAG = "NettyService ";

    public NettyService() {
    }

    @Override
    public void onCreate() {
        super.onCreate();
        setNotificationAndForeground();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        NettyClient.start();
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    }

    @Override
    public void onDestroy() {
        Log.e(TAG, "onDestroy: 服务被杀");
        NettyClient.close();
        super.onDestroy();
    }


    //设置前台服务通知
    @SuppressLint("ForegroundServiceType")
    public void setNotificationAndForeground(){
        String ChannelId = "TALK_ID";
        NotificationChannel notificationChannel = new NotificationChannel(ChannelId, "畅聊前台服务", NotificationManager.IMPORTANCE_HIGH);
        notificationChannel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC); //设置前台服务锁屏可见
        NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        manager.createNotificationChannel(notificationChannel);
        Notification notification = new Notification.Builder(this, ChannelId)
                .setAutoCancel(false) //点击后不会取消
                .setContentText("畅聊正在后台运行")
                .setSmallIcon(R.drawable.app_logo)
                .setOngoing(true)
                .build();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE){
            startForeground(1,notification, ServiceInfo.FOREGROUND_SERVICE_TYPE_REMOTE_MESSAGING);
        }else {
            startForeground(1,notification);
        }

    }

}